package comptest;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * @version 1.8
 * @Author Djx_hmbb
 * @Date 2023/8/5 12:48
 * @注释:JDBCInsert
 * insert/update/delete-->executeUpdate
 */
public class JDBCInsert {
    public static void main(String[] args) throws SQLException {
        //1.创建并初始化一个数据源
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/stu?serverTimezone=GMT%2B8&userSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2.和数据库服务器连接
        Connection connection = (Connection) dataSource.getConnection();
        //3.构造SQL语句；
        String sql = "insert into goods values(null,?,?,?,?)";
        PreparedStatement pms = connection.prepareStatement(sql);
            //输入
        Scanner s = new Scanner(System.in);
        System.out.println("商品名称:");
//        String name = s.next();
        pms.setString(1, s.next());
        System.out.println("价格:");
//        double d = s.nextDouble();
        pms.setDouble(2,s.nextDouble());
        System.out.println("库存:");
//        int i = s.nextInt();
        pms.setInt(3,s.nextInt());
        System.out.println("描述:");
//        String ss = s.next();
        pms.setString(4,s.next());
        //4.执行SQL语句
        int ret = pms.executeUpdate();
        System.out.println(ret);
        //5.释放必要的资源
        pms.close();
        connection.close();
    }
}
